package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"math"
	"novel/cache"
	"novel/models"
)

type ReadController struct {
	beego.Controller
}

func (c *ReadController) Page() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	models.DB.Model(&models.Read{}).Count(&count)
	sum := int(math.Ceil(float64(count) / float64(size)))
	offset := (page - 1) * size
	var novelId []interface{}
	userId, _ := c.GetInt("user_id")
	models.DB.Model(&models.Read{}).Select("novel_id").Where("user_id=?", userId).Find(&novelId)
	var novels []models.Novel
	models.DB.Where("id in (?)", novelId).Offset(offset).Limit(size).Find(&novels)
	c.Data["json"] = map[string]interface{}{
		"code":  500,
		"msg":   "展示成功",
		"data":  novels,
		"page":  page,
		"size":  size,
		"sum":   sum,
		"count": count,
	}
	c.ServeJSON()
	return
}
func (c *ReadController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	cacheData := cache.Rdb.Get(cache.Ctx, "list").Val()
	var novels []models.Novel
	if cacheData == "" {
		var novelId []interface{}
		userId, _ := c.GetInt("user_id")
		models.DB.Model(&models.Read{}).Select("novel_id").Where("user_id=?", userId).Find(&novelId)
		models.DB.Where("id in (?)", novelId).Find(&novels)
		jsonData, _ := json.Marshal(novels)
		cache.Rdb.Set(cache.Ctx, "lie", jsonData, 0)
	} else {
		json.Unmarshal([]byte(cacheData), &novels)
	}
	c.Data["json"] = map[string]interface{}{
		"code": 500,
		"msg":  "展示成功",
		"data": novels,
	}
	c.ServeJSON()
	return
}
func (c *ReadController) Del() {
	id, _ := c.GetInt("id")
	var reads models.Read
	models.DB.Where("id=?", reads).Find(&reads)
	if reads.Type == "已完成阅读" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "已完成阅读禁止删除",
		}
		c.ServeJSON()
		return
	}
	reads.ID = uint(id)
	err := reads.Del()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "删除失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "删除成功",
	}
	c.ServeJSON()
	return
}
